package com.itheima.utils;

import java.sql.Connection;

import javax.sql.DataSource;

/**
 * ClassName:ConnectionUtils
 * Package:com.itheima.utils
 * Description:连接的工具类，用于从数据源中获取一个连接，并且实现和线程的绑定
 * Date:2020/2/22 22:29
 * User: snow
 */
public class ConnectionUtils {

	private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	/**
	 * 获取当前线程上的连接connection
	 *
	 * @return
	 */
	public Connection getThreadConnection() {
		try {
			// 1、先从ThreadLocation上获取
			Connection connection = threadLocal.get();
			// 2、判断当前线程上是否有连接
			if (connection == null) {
				// 3、从数据源中获取一个连接，并且存入ThreadLocation
				connection = dataSource.getConnection();
				threadLocal.set(connection);
			}
			// 4、返回当前线程上的连接
			return connection;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 解除连接和线程的绑定
	 */
	public void removeConnection() {
		threadLocal.remove();
	}
}
